﻿using Camera_NET;
using Newtonsoft.Json;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace OCR
{
    public partial class NewMain : Form
    {

        //显示计数委托
        private delegate void dgShowCount(string source, int i);
        //显示识别结果委托
        private delegate void dgShowRecognitionValue(string noValue, string pwValue);
        //显示原图委托
        private delegate void dgShowBitmap(Bitmap bitmap);
        //光电开关计数委托
        private dgOpticalSwitchCount opticalSwitchCount;
        //发送消息委托
        private delegate void dgSendMessage(string message);

        // 待识别图片文件队列
        private static Queue<string> imageFileQueue = new Queue<string>();
        // 为保证线程安全，使用一个锁来保护_task的访问
        private readonly static object _locker = new object();
        // 通过 _wh 给工作线程发信号
        private static EventWaitHandle _wh;
        //识别工作线程任务
        private static Thread threadRecognition;

        //识别结果列表
        private List<Card> cards = new List<Card>();
        //图片计数
        private int captureCount = 0;
        //可疑卡号计数
        private int noDoubtCount = 0;
        //可疑密码计数
        private int pwDoubtCount = 0;

        //宽度比例
        private float widthRate;
        //高度比例
        private float heightRate;
        //开始时间
        private DateTime beginTime;
        //结束时间
        private DateTime endTime;
        //自动识别开关,默认关闭
        private bool autoRecognition = false;
        //配置选择项
        private int configSelectIndex = 0;
        //存储文件夹
        private string saveFolder = OCR.SaveRootFolder;
        //当前正在使用的配置方案，实时更新
        public CardType curCardType;
        //选择配置(不会实时更新，保存时统一更新)
        private CardType selectCardType;
        //摄像头
        private CameraChoice cameraChoice = new CameraChoice();
        //延时
        private int delayTime = 190;


        private RegionView regionView;
        //分辨率
        ResolutionList resolutions;
        public NewMain()
        {
            InitializeComponent();
        }
        /// <summary>
        /// 初始化值
        /// </summary>
        private void Init()
        {
            //运营商
            this.cbFactoryName.SelectedIndex = 0;
            //面值
            this.cbFaceValue.SelectedIndex = 0;
            //有效期
            this.dpValidDate.Value = DateTime.Now;


            //延时初始化
            if (!string.IsNullOrEmpty(Properties.Settings.Default.DelayTime))
            {
                this.tsDelayTime.Text = Properties.Settings.Default.DelayTime + "秒";

                this.delayTime = Convert.ToInt32(decimal.Parse(Properties.Settings.Default.DelayTime) * 1000);
                foreach (ToolStripMenuItem m in this.tsDelayTime.DropDownItems)
                {
                    if (m.Tag.ToString() == Properties.Settings.Default.DelayTime)
                    {
                        m.Checked = true;
                    }
                    else
                    {
                        m.Checked = false;
                    }
                }
            }
            //识别方法
            foreach (string item in Enum.GetNames(typeof(识别方法)))
            {
                this.cbNoRegType.Items.Add(item);
                this.cbPwRegType.Items.Add(item);
            }
            this.cbNoRegType.SelectedIndex = 0;
            this.cbPwRegType.SelectedIndex = 0;
            //字体
            string fonts = System.Configuration.ConfigurationManager.AppSettings["font"].ToString();
            if (!string.IsNullOrEmpty(fonts))
            {
                this.cbNoFont.Items.AddRange(fonts.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries));
                this.cbPwFont.Items.AddRange(fonts.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries));
                this.cbNoFont.SelectedIndex = 0;
                this.cbPwFont.SelectedIndex = 0;
            }
            //源图片

            this.tsSourceFolder.Tag = Properties.Settings.Default.SourceFoldPath;
            if (this.tsSourceFolder.Tag != null && this.tsSourceFolder.Tag.ToString() != "")
            {
                this.tsSourceFolder.Text = Path.GetPathRoot(this.tsSourceFolder.Tag.ToString()) + @"...\" + Path.GetFileName(this.tsSourceFolder.Tag.ToString());
            }
            else
            {
                this.tsSourceFolder.Text = "";
            }
            //光电开光
            switch (OpticalSwitch.GetPower1())
            {
                case -1:
                    this.tsSwitchOnOff.Text = "未接设备";
                    break;
                case 0:
                    this.tsSwitchOnOff.Text = "关";
                    break;
                case 1:
                    this.tsSwitchOnOff.Text = "开";
                    OpticalSwitch.InitCount(); //初始化光电开关计数
                    //委托自动计数函数
                    opticalSwitchCount = new dgOpticalSwitchCount(AutoOpticalSwitchCount);
                    OpticalSwitch.SetCount(opticalSwitchCount);
                    //打开摄像头
                    OpenCamera();
                    break;
                default:
                    this.tsSwitchOnOff.Text = "未知";
                    break;
            }
        }

        private void NewMain_Load(object sender, EventArgs e)
        {
            //控件初始化
            this.Init();
            //加载默认配置项
            LoadDefaultConfigs();
            //显示面板
            EnableViewPanel();

            if (this.tsMode.Text == "拍照识别")
            {
                this.lbCaptureTip.Visible = true;
            }
        }
        /// <summary>
        /// 光电开关自动计数
        /// </summary>
        /// <param name="index"></param>
        /// <param name="count"></param>
        private void AutoOpticalSwitchCount(int index, int count)
        {
            try
            {
                DateTime beginCaptureTime = DateTime.Now;
                //光电开关计数
                this.tsSwitchCount.Text = count.ToString();
                if (this.autoRecognition)
                {
                    Thread.Sleep(this.delayTime);
                    if (cameraControl.CameraCreated)
                    {
                        Bitmap bitmap = cameraControl.SnapshotSourceImage();
                        if (bitmap != null)
                        {
                            //结束不可用
                            this.btStart.Enabled = false;
                            //压缩保存原图
                            string saveFileFullName = Path.Combine(this.saveFolder, DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss.fff") + ".jpg");
                            BitmapHelper.SaveSmallImage(bitmap, saveFileFullName);
                            //向列队插入文件名称
                            EnqueueTask(saveFileFullName);
                            DateTime endCaptureTime = DateTime.Now;
                            this.tsCaptureTimeSpan.Text = "拍照存储：" + OCR.TimeSpan(beginCaptureTime, endCaptureTime, 分秒毫秒.秒毫秒);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                this.tsTip.Text = ex.Message;
            }
        }

        /// <summary>
        /// 图片自动识别
        /// </summary>
        private void AutoPictureReg(object arg)
        {
            string[] filePaths = (string[])arg;
            int i = 0;
            foreach (string filePath in filePaths)
            {
                i++;
                if (this.autoRecognition)
                {
                    Bitmap bitmap = new Bitmap(filePath);

                    //压缩保存原图
                    string fileName = Path.GetFileName(filePath);
                    string saveFileFullName = Path.Combine(this.saveFolder, fileName);
                    BitmapHelper.SaveSmallImage(bitmap, saveFileFullName);
                    //识别图片
                    Recognition(saveFileFullName);
                    //更新进度条
                    this.BeginInvoke(new dgShowCount(ShowCount), "进度条", i);
                }
                else
                {
                    //退出识别
                    break;
                }
            }
            //有调整
            if (CardManager.Cards.Exists(d => d.IsNoDoubt || d.IsPwDoubt))
            {
                Adjust frm = new Adjust(this.saveFolder, CardManager.Cards);
                if (frm.ShowDialog() == System.Windows.Forms.DialogResult.OK)//调整结束
                {
                    this.noDoubtCount = 0;
                    this.pwDoubtCount = 0;
                    this.BeginInvoke(new dgShowCount(ShowCount), "卡号", this.noDoubtCount);
                    this.BeginInvoke(new dgShowCount(ShowCount), "密码", this.pwDoubtCount);
                }
            }
            //保存识别结果
            SaveHistory();
            //导出可用
            this.BeginInvoke(new dgSendMessage(AutoPictureRegComplete), "图片识别完成！");
        }
        private void EnqueueTask(string fileFullName)
        {
            lock (_locker)
            {
                imageFileQueue.Enqueue(fileFullName);  // 向队列中插入任务 
                this.BeginInvoke(new dgShowCount(ShowCount), "进度条", imageFileQueue.Count);
            }
            _wh.Set();  // 给工作线程发信号
        }
        /// <summary>执行识别工作</summary>
        private void RecognitionWork()
        {
            while (true)
            {
                string work = null;
                lock (_locker)
                {
                    if (imageFileQueue.Count > 0)
                    {
                        work = imageFileQueue.Dequeue(); // 取出文件名称

                        if (work == null)  // 退出机制：当遇见一个null任务时，代表任务结束
                            return;
                    }
                }

                if (work != null)
                {
                    Recognition(work);  // 任务不为null时，处理并保存数据
                }
                else
                {
                    //识别结束，可以点击关闭
                    this.BeginInvoke(new dgSendMessage(AutoCaptureRegComplete), "识别结束");
                    _wh.WaitOne();   // 没有任务了，等待信号
                }

                //动态处理进度条
                this.BeginInvoke(new dgShowCount(ShowCount), "进度条", imageFileQueue.Count);
            }
        }

        private void AutoCaptureRegComplete(string message)
        {
            this.progressBar1.Value = 0;
            this.btStart.Enabled = true;
        }
        //识别图片
        private void Recognition(string fileFullName)
        {
            DateTime beginTime = DateTime.Now;
            Card card = new Card();
            card.Define = this.curCardType;
            card.ImageName = Path.GetFileNameWithoutExtension(fileFullName);
            Bitmap image = new Bitmap(fileFullName);

            //识别区域图
            Bitmap noCharImage, noBarCodeImage, pwCharImage, pwBarCodeImage;
            //卡号字符扣图
            noCharImage = BitmapHelper.CutProcessImage(image, this.curCardType.NoRecognition.CharRecognition.Region, BinarizationMethods.Otsu, this.curCardType.NoRecognition.CharRecognition.NoiseClear);
            //保存卡号
            noCharImage.Save(Path.Combine(Path.GetDirectoryName(fileFullName), card.NoImageName));
            //先识别
            card.NoRecognitionValue.CharValue = OCR.CharRecognition(noCharImage, OCR.FontFolderPath, this.curCardType.NoRecognition.CharRecognition.Font, this.curCardType.NoRecognition.CharRecognition.RecognitionStr);

            if (this.curCardType.NoRecognition.Type == 识别方法.条形码 || this.curCardType.NoRecognition.Type == 识别方法.混合)
            {
                //卡号条形码扣图，条形码码不用保存
                noBarCodeImage = BitmapHelper.CutProcessImage(image, this.curCardType.NoRecognition.BarCodeRecognition.Region, BinarizationMethods.Otsu, this.curCardType.NoRecognition.BarCodeRecognition.NoiseClear);
                //先识别
                card.NoRecognitionValue.BarCodeValue = OCR.BarCodeRecognition(noBarCodeImage);

            }

            //密码字符扣图
            pwCharImage = BitmapHelper.CutProcessImage(image, this.curCardType.PwRecognition.CharRecognition.Region, BinarizationMethods.Otsu, this.curCardType.PwRecognition.CharRecognition.NoiseClear);
            card.PwRecognitionValue.CharValue = OCR.CharRecognition(pwCharImage, OCR.FontFolderPath, this.curCardType.PwRecognition.CharRecognition.Font, this.curCardType.PwRecognition.CharRecognition.RecognitionStr);
            //保存密码
            pwCharImage.Save(Path.Combine(Path.GetDirectoryName(fileFullName), card.PwImageName));

            if (this.curCardType.PwRecognition.Type == 识别方法.条形码 || this.curCardType.PwRecognition.Type == 识别方法.混合)
            {
                //密码条形码扣图，条形码码不用保存
                pwBarCodeImage = BitmapHelper.CutProcessImage(image, this.curCardType.PwRecognition.BarCodeRecognition.Region, BinarizationMethods.Otsu, this.curCardType.PwRecognition.BarCodeRecognition.NoiseClear);
                //先识别
                card.PwRecognitionValue.BarCodeValue = OCR.BarCodeRecognition(pwBarCodeImage);
            }
            //计数显示
            if (card.IsNoDoubt)
            {
                this.noDoubtCount++;
                this.BeginInvoke(new dgShowCount(ShowCount), "卡号", this.noDoubtCount);
            }
            if (card.IsPwDoubt)
            {
                this.pwDoubtCount++;
                this.BeginInvoke(new dgShowCount(ShowCount), "密码", this.pwDoubtCount);
            }

            this.captureCount++;
            this.lbCount.BeginInvoke(new dgShowCount(ShowCount), "图片", this.captureCount);

            //显示原图
            this.BeginInvoke(new dgShowBitmap(ShowSourceImage), image);

            //显示识别结果
            this.BeginInvoke(new dgShowRecognitionValue(ShowValue), card.NoValue, card.PwValue);
            //显示识别区域图片
            if (this.regionView != null && this.regionView.Visible)
            {
                this.BeginInvoke(new dgShowBitmap(ShowRegionImage), image);
            }
            DateTime endTime = DateTime.Now;
            string spanTime = OCR.TimeSpan(beginTime, endTime, 分秒毫秒.秒毫秒);
            this.BeginInvoke(new dgSendMessage(ShwoRegTimeSpan), spanTime);
            CardManager.Cards.Add(card);
        }
        private void ShwoRegTimeSpan(string message)
        {
            this.tsRegTimeSpan.Text = message;
        }
        private void ShowValue(string noValue, string pwValue)
        {
            this.lbNoCharValue.Text = noValue;
            //    this.lbNoBarCodeValue.Text = noBarCodeValue;
            this.lbPwCharValue.Text = pwValue;
            //  this.lbPwBarCodeValue.Text = pwBarCodeValue;
        }
        /// <summary>
        /// 图片识别完成
        /// </summary>
        private void AutoPictureRegComplete(string message)
        {
            this.btAdjust.Enabled = true;
            //导出可用
            this.btExportExcel.Enabled = true;
            //可以开始
            this.btStart.Text = "开始";
            this.progressBar1.Value = 0;
        }
        /// <summary>
        /// 结束可用
        /// </summary>
        private void btAdjust_Click(object sender, EventArgs e)
        {
            Adjust frm = new Adjust(this.saveFolder, CardManager.Cards);
            if (frm.ShowDialog() == System.Windows.Forms.DialogResult.OK)//调整结束
            {
                this.noDoubtCount = 0;
                this.pwDoubtCount = 0;
                ShowCount("卡号", this.noDoubtCount);
                ShowCount("密码", this.pwDoubtCount);
                //保存识别结果
                SaveHistory();
            }
        }
        /// <summary>
        /// 显示识别区域图
        /// </summary>
        /// <param name="noCharImage"></param>
        /// <param name="noBarCodeImage"></param>
        /// <param name="pwCharImage"></param>
        /// <param name="pwBarCodeImage"></param>
        private void ShowRegionImage(Bitmap sourceBitmap)
        {
            this.regionView.ShowImage(this.curCardType, sourceBitmap);
        }
        /// <summary>
        /// 显示原图
        /// </summary>
        /// <param name="image"></param>
        private void ShowSourceImage(Bitmap image)
        {
            this.pbPreview.Image = image;
            this.pbPreview.Refresh();
        }
        private void ShowCount(string source, int i)
        {
            if (source == "图片")
            {
                this.lbCount.Text = i.ToString();
            }
            else if (source == "卡号")
            {
                this.lbNoErrorCount.Text = i.ToString();
            }
            else if (source == "密码")
            {
                this.lbPwErrorCount.Text = i.ToString();
            }
            else if (source == "进度条")
            {
                this.progressBar1.Value = i;
            }
        }

        //打开摄像头
        private void OpenCamera()
        {
            FillCameraList();
            FillResolutionList();
        }
        /// <summary>
        /// 填充摄像头列表并打开
        /// </summary>
        private void FillCameraList()
        {
            this.tsCameraSource.DropDownItems.Clear();
            //更新摄像头列表
            this.cameraChoice.UpdateDeviceList();

            if (cameraChoice.Devices != null && cameraChoice.Devices.Count > 0)
            {
                foreach (var camera_device in cameraChoice.Devices)
                {
                    ToolStripMenuItem item = new ToolStripMenuItem();
                    item.Text = camera_device.Name;
                    item.Name = camera_device.Name;
                    this.tsCameraSource.DropDownItems.Add(item);
                }
                if (this.tsCameraSource.DropDownItems.Count > 0)
                {
                    ((ToolStripMenuItem)this.tsCameraSource.DropDownItems[0]).Checked = true;

                    cameraControl.SetCamera(this.cameraChoice.Devices[0].Mon, null);
                }
            }
        }
        //填充分辨率列表
        private void FillResolutionList()
        {
            this.tsPix.DropDownItems.Clear();

            if (!cameraControl.CameraCreated)
                return;
            resolutions = Camera.GetResolutionList(cameraControl.Moniker);
            if (resolutions == null)
                return;

            for (int index = 0; index < resolutions.Count; index++)
            {
                ToolStripMenuItem item = new ToolStripMenuItem();
                //名称等于索引
                item.Name = resolutions[index].ToString();
                item.Text = resolutions[index].ToString();
                item.Tag = index;
                this.tsPix.DropDownItems.Add(item);
                if (!string.IsNullOrEmpty(Properties.Settings.Default.Fix))
                {
                    if (resolutions[index].ToString() == Properties.Settings.Default.Fix)
                    {
                        item.Checked = true;
                        cameraControl.SetCamera(cameraControl.Moniker, resolutions[index]);
                    }
                }
                else
                {
                    if (resolutions[index].CompareTo(cameraControl.Resolution) == 0)
                    {
                        item.Checked = true;
                    }
                }

                item.Click += FixClick;
            }

        }

        /// <summary>
        /// 右键按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void FixClick(object sender, EventArgs e)
        {
            ToolStripMenuItem ts = sender as ToolStripMenuItem;
            foreach (ToolStripMenuItem item in this.tsPix.DropDownItems)
            {
                item.Checked = false;
                if (item.Text == ts.Text)
                {
                    cameraControl.SetCamera(cameraControl.Moniker, resolutions[(int)ts.Tag]);
                    ts.Checked = true;
                    Properties.Settings.Default.Fix = ts.Text;
                    Properties.Settings.Default.Save();
                }
            }
        }

        #region 右键操作

        /// <summary>
        /// 拍照一张
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsCapturePicture_Click(object sender, EventArgs e)
        {
            if (this.cameraControl.CameraCreated)
            {
                Bitmap bitmap = cameraControl.SnapshotOutputImage();
                if (bitmap != null)
                {
                    this.lbCaptureTip.Visible = false;
                    this.pbPreview.Image = bitmap;
                    this.widthRate = (float)this.pbPreview.Size.Width / (float)this.pbPreview.Image.Size.Width;
                    this.heightRate = (float)this.pbPreview.Size.Height / (float)this.pbPreview.Image.Size.Height;
                    this.pbPreview.Refresh();

                }
            }
        }

        private void tsDelayTime_Click(object sender, EventArgs e)
        {
            ToolStripMenuItem ts = (sender as ToolStripMenuItem);
            foreach (ToolStripMenuItem m in this.tsDelayTime.DropDownItems)
            {
                m.Checked = false;
            }
            this.delayTime = (int)(Convert.ToDecimal(ts.Tag.ToString()) * 1000);
            ts.Checked = true;
            this.tsDelayTime.Text = ts.Text;
            Properties.Settings.Default.DelayTime = ts.Tag.ToString();
            Properties.Settings.Default.Save();
        }

        #endregion

        #region 配置项操作

        private void FillConfigs()
        {
            //清空列表
            this.cbCardType.Items.Clear();

            foreach (CardType info in CardTypeManager.CardTypes)
            {
                this.cbCardType.Items.Add(info.Name);
            }

        }
        /// <summary>
        /// 加载默认配置
        /// </summary>
        private void LoadDefaultConfigs()
        {


            if (CardTypeManager.CardTypes == null || CardTypeManager.CardTypes.Count == 0)
            {
                //初始化第一个配置
                this.curCardType = new CardType();
                //当前配置名称
                this.tbCardTypeName.Text = this.cbFactoryName.Text + "(" + this.cbFaceValue.Text + ")";
                //赋值
                SetCardType(this.curCardType);
                CardTypeManager.AddCardType(this.curCardType);
            }
            //填充cbConfigs
            FillConfigs();
            string defaultconfigName = Properties.Settings.Default.ConfigSchemeName;
            if (!string.IsNullOrEmpty(defaultconfigName))
            {
                //显示默认值选项
                this.cbCardType.SelectedItem = defaultconfigName;
            }
            else
            {
                //没有默认值显示第一个
                this.cbCardType.SelectedIndex = 0;
            }
        }
        //设置配置值
        private void SetCardType(CardType cardType)
        {
            cardType.Name = this.tbCardTypeName.Text;//方案名称
            cardType.FactoryName = this.cbFactoryName.Text;//运营商
            cardType.FaceValue = this.cbFaceValue.Text;//面值
            cardType.ValidDate = this.dpValidDate.Value;//有效期
            //卡号识别
            cardType.NoRecognition.Type = (识别方法)Enum.Parse(typeof(识别方法), this.cbNoRegType.Text);
            cardType.NoRecognition.CharRecognition.Font = this.cbNoFont.Text;//字体
            cardType.NoCount = (int)this.nbNoCount.Value;//卡号位数
            cardType.NoRecognition.CharRecognition.RecognitionNum = this.ckbNoNum.Checked;//数字
            cardType.NoRecognition.CharRecognition.RecognitionChar = this.ckbNoCharacter.Checked;//字母

            //密码识别
            cardType.PwRecognition.Type = (识别方法)Enum.Parse(typeof(识别方法), this.cbPwRegType.Text);
            cardType.PwRecognition.CharRecognition.Font = this.cbPwFont.Text;//字体
            cardType.PwCount = (int)this.nbPwCount.Value;//卡号位数
            cardType.PwRecognition.CharRecognition.RecognitionNum = this.ckbPwNum.Checked;//数字
            cardType.PwRecognition.CharRecognition.RecognitionChar = this.ckbPwCharacter.Checked;//字母
        }
        //显示配置值
        private void ShowCofig(CardType cardType)
        {
            this.tbCardTypeName.Text = cardType.Name;//方案名称
            this.cbFactoryName.Text = cardType.FactoryName;
            this.cbFaceValue.Text = cardType.FaceValue.ToString();
            this.dpValidDate.Value = cardType.ValidDate;
            //卡号
            this.cbNoRegType.Text = cardType.NoRecognition.Type.ToString();
            this.cbNoFont.Text = cardType.NoRecognition.CharRecognition.Font.ToString();
            this.nbNoCount.Value = cardType.NoCount;
            this.ckbNoNum.Checked = cardType.NoRecognition.CharRecognition.RecognitionNum;
            this.ckbNoCharacter.Checked = cardType.NoRecognition.CharRecognition.RecognitionChar;

            //密码
            this.cbPwRegType.Text = cardType.PwRecognition.Type.ToString();
            this.cbPwFont.Text = cardType.PwRecognition.CharRecognition.Font.ToString();
            this.nbPwCount.Value = cardType.PwCount;
            this.ckbPwNum.Checked = cardType.PwRecognition.CharRecognition.RecognitionNum;
            this.ckbPwCharacter.Checked = cardType.PwRecognition.CharRecognition.RecognitionChar;
        }

        private void cbConfig_SelectedIndexChanged(object sender, EventArgs e)
        {
            //至少有一个，不存在小于
            if (this.cbCardType.Items.Count > 0)
            {
                this.selectCardType = CardTypeManager.CardTypes.Find(d => d.Name == this.cbCardType.SelectedItem.ToString());
                //显示配置值
                ShowCofig(selectCardType);
                this.curCardType = new CardType();
                SetCardType(this.curCardType);
                //当前卡类型等于选择卡类型
                this.curCardType.NoRecognition.CharRecognition.Region = this.selectCardType.NoRecognition.CharRecognition.Region;
                this.curCardType.NoRecognition.BarCodeRecognition.Region = this.selectCardType.NoRecognition.BarCodeRecognition.Region;
                this.curCardType.PwRecognition.CharRecognition.Region = this.selectCardType.PwRecognition.CharRecognition.Region;
                this.curCardType.PwRecognition.BarCodeRecognition.Region = this.selectCardType.PwRecognition.BarCodeRecognition.Region;

                this.curCardType.NoRecognition.CharRecognition.NoiseClear = this.selectCardType.NoRecognition.CharRecognition.NoiseClear;
                this.curCardType.NoRecognition.BarCodeRecognition.NoiseClear = this.selectCardType.NoRecognition.BarCodeRecognition.NoiseClear;
                this.curCardType.PwRecognition.CharRecognition.NoiseClear = this.selectCardType.PwRecognition.CharRecognition.NoiseClear;
                this.curCardType.PwRecognition.BarCodeRecognition.NoiseClear = this.selectCardType.PwRecognition.BarCodeRecognition.NoiseClear;

                this.configSelectIndex = this.cbCardType.SelectedIndex;
                //配置方案更改后，程序默认值保存到本地
                Properties.Settings.Default.ConfigSchemeName = this.cbCardType.SelectedItem.ToString();
                Properties.Settings.Default.Save();


            }
            if (this.pbPreview.Image != null)
            {
                //画区域
                this.pbPreview.Refresh();//发送图片重绘消息
                if (this.regionView != null && this.regionView.Visible)
                {
                    this.regionView.ShowImage(this.curCardType, (Bitmap)this.pbPreview.Image);
                }
            }
        }


        /// <summary>
        /// 删除配置方案
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btDel_Click(object sender, EventArgs e)
        {
            //至少保留一个
            if (this.cbCardType.Items.Count > 1)
            {
                if (MessageBox.Show("是否删除？", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
                {
                    CardTypeManager.Del(this.selectCardType);

                    //重新填充控件
                    this.FillConfigs();
                    //默认选择第一项
                    this.cbCardType.SelectedIndex = 0;

                }
            }
            else
            {
                MessageBox.Show("最少有一个配置，不允许删除");
            }
        }
        #endregion

        #region 框选、移动图片

        Point start; //鼠标点击起始点
        bool isDraw;//判断是否左键绘制
        Rectangle rect;//框选区域

        private void pbPreview_MouseDown(object sender, MouseEventArgs e)
        {
            // 按下鼠标右键，记录鼠标按下的位置
            start = e.Location;
            if (e.Button == MouseButtons.Left && this.btStart.Text != "结束")
            {
                // Invalidate();
                isDraw = true;
            }

        }

        private void pbPreview_MouseMove(object sender, MouseEventArgs e)
        {
            if (isDraw)
            {
                if (e.Button != MouseButtons.Left)//判断是否按下左键
                    return;
                Point tempEndPoint = e.Location; //记录框的位置和大小
                rect.Location = new Point(Math.Min(start.X, tempEndPoint.X), Math.Min(start.Y, tempEndPoint.Y));
                rect.Size = new Size(Math.Abs(start.X - tempEndPoint.X), Math.Abs(start.Y - tempEndPoint.Y));
                this.pbPreview.Invalidate();//发送图片重绘消息
            }
        }

        private void pbPreview_MouseUp(object sender, MouseEventArgs e)
        {
            if (e.Button == System.Windows.Forms.MouseButtons.Left)
            {
                this.isDraw = false; //结束绘制
                if (this.pbPreview.Image != null && this.btStart.Text != "结束")
                {
                    //绘制区域过小
                    if (this.rect.Width * this.rect.Height > 3000)
                    {
                        this.scContent.Panel2.Enabled = false;
                        this.plTop.Enabled = false;
                        this.plSelection.Visible = true;
                        //弹出对话框定位
                        int x = System.Windows.Forms.Cursor.Position.X;
                        int y = System.Windows.Forms.Cursor.Position.Y;
                        Point curPoint = this.Location;
                        this.plSelection.Location = new Point(x - curPoint.X < 204 ? 0 : x - curPoint.X - 209, y - curPoint.Y - 28);
                    }
                }

            }
        }
        private void pbPreview_Paint(object sender, PaintEventArgs e)
        {
            if (this.isDraw)
            {
                if (this.pbPreview.Image != null)
                {
                    if (rect != null && rect.Width > 0 && rect.Height > 0)
                    {

                        e.Graphics.DrawRectangle(new Pen(Color.Red, 2), rect);//重新绘制颜色为红色
                    }
                }
            }
            else
            {
                if (this.pbPreview.Image != null)
                {
                    //变形画区域
                    e.Graphics.DrawRectangle(new Pen(Color.Blue, 2), OCR.RectangleChange(this.curCardType.NoRecognition.CharRecognition.Region, this.widthRate, this.heightRate, false));
                    e.Graphics.DrawRectangle(new Pen(Color.Blue, 2), OCR.RectangleChange(this.curCardType.NoRecognition.BarCodeRecognition.Region, this.widthRate, this.heightRate, false));
                    e.Graphics.DrawRectangle(new Pen(Color.Red, 2), OCR.RectangleChange(this.curCardType.PwRecognition.CharRecognition.Region, this.widthRate, this.heightRate, false));
                    e.Graphics.DrawRectangle(new Pen(Color.Red, 2), OCR.RectangleChange(this.curCardType.PwRecognition.BarCodeRecognition.Region, this.widthRate, this.heightRate, false));
                }
            }
        }

        private void btOk_Click(object sender, EventArgs e)
        {
            this.scContent.Panel2.Enabled = true;
            this.plTop.Enabled = true;
            this.plSelection.Visible = false;

            //卡号字符
            if (this.rbNoCharSelect.Checked)
            {
                this.curCardType.NoRecognition.CharRecognition.Region = OCR.RectangleChange(rect, this.widthRate, this.heightRate, true);//还原为真实图片大小;
            }
            //卡号条形码
            else if (this.rbNoBarCodeSelect.Checked)
            {
                this.curCardType.NoRecognition.BarCodeRecognition.Region = OCR.RectangleChange(rect, this.widthRate, this.heightRate, true);//还原为真实图片大小;
            }
            //密码字符
            if (this.rbPwCharSelect.Checked)
            {
                this.curCardType.PwRecognition.CharRecognition.Region = OCR.RectangleChange(rect, this.widthRate, this.heightRate, true);//还原为真实图片大小;
            }
            else if (this.rbPwBarCodeSelect.Checked)
            {
                this.curCardType.PwRecognition.BarCodeRecognition.Region = OCR.RectangleChange(rect, this.widthRate, this.heightRate, true);//还原为真实图片大小;
            }
            this.pbPreview.Refresh();

            //是否显示区域图像
            if (this.regionView != null && this.regionView.Visible)
            {
                this.regionView.ShowImage(this.curCardType, (Bitmap)this.pbPreview.Image);
            }
        }

        #endregion


        private void btStart_Click(object sender, EventArgs e)
        {
            if (this.btStart.Text == "开始")
            {
                this.lbTimeSpan.Text = "";
                if (this.curCardType.NoRecognition.CharRecognition.Region.Width * this.curCardType.NoRecognition.CharRecognition.Region.Height * this.curCardType.PwRecognition.CharRecognition.Region.Width * this.curCardType.PwRecognition.CharRecognition.Region.Height == 0)
                {
                    MessageBox.Show("请选框选卡号和密码识别区域");
                    return;
                }

                if (this.curCardType.NoRecognition.Type == 识别方法.条形码 || this.curCardType.NoRecognition.Type == 识别方法.混合)
                {
                    if (this.curCardType.NoRecognition.BarCodeRecognition.Region.Width * this.curCardType.NoRecognition.BarCodeRecognition.Region.Height == 0)
                    {
                        MessageBox.Show("卡号条形码识别区域未框选!");
                        return;
                    }
                }
                if (this.curCardType.PwRecognition.Type == 识别方法.条形码 || this.curCardType.PwRecognition.Type == 识别方法.混合)
                {
                    if (this.curCardType.PwRecognition.BarCodeRecognition.Region.Width * this.curCardType.PwRecognition.BarCodeRecognition.Region.Height == 0)
                    {
                        MessageBox.Show("密码条形码识别区域未框选!");
                        return;
                    }
                }
                this.beginTime = DateTime.Now;
                //计数都为零
                this.captureCount = 0;
                this.lbCount.Text = "0";
                this.lbNoErrorCount.Text = "0";
                this.lbPwErrorCount.Text = "0";
                OpticalSwitch.InitCount(); //初始化光电开关计数
                this.tsSwitchCount.Text = "0";//光电开关计数为零
                this.progressBar1.Minimum = 0;
                this.progressBar1.Value = 0;
                this.progressBar1.Maximum = 100;

                CardManager.Cards.Clear();
                //拍照识别模式，采取生产者、消费都模式，以不影响拍照
                if (this.tsMode.Text == "拍照识别")
                {
                    if (this.tsSwitchOnOff.Text == "开")
                    {
                        if (this.cameraControl.CameraCreated)
                        {
                            this.saveFolder = Path.Combine(OCR.SaveRootFolder, DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss"));

                            Directory.CreateDirectory(this.saveFolder);
                            this.autoRecognition = true;
                            this.btStart.Text = "结束";
                            this.btAdjust.Enabled = false;
                            this.btExportExcel.Enabled = false;
                            this.tsTip.Text = "开始传送卡片，点击【结束】结束识别";

                            _wh = new AutoResetEvent(false);
                            // 识别任务开始，启动识别工作线程，消费者
                            threadRecognition = new Thread(RecognitionWork);
                            threadRecognition.Start();
                        }
                        else
                        {
                            MessageBox.Show("摄像头未打开!");
                        }
                    }
                    else
                    {
                        MessageBox.Show("光电开关未打开!");
                    }
                }
                else//图片识别模式
                {
                    if (Directory.Exists(this.tsSourceFolder.Tag.ToString()))
                    {
                        //打开自动识别
                        this.autoRecognition = true;
                        string[] filePaths = Directory.GetFiles(this.tsSourceFolder.Tag.ToString(), "*.jpg", SearchOption.TopDirectoryOnly);
                        if (filePaths != null)
                        {
                            this.btAdjust.Enabled = false;
                            this.btExportExcel.Enabled = false;
                            this.btStart.Text = "结束";
                            this.progressBar1.Visible = true;
                            this.progressBar1.Minimum = 0;
                            this.progressBar1.Value = 0;
                            this.progressBar1.Maximum = filePaths.Length;

                            this.tsTip.Text = "点击【结束】可以结束当前卡片识别！";

                            this.saveFolder = Path.Combine(OCR.SaveRootFolder, DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss"));
                            Directory.CreateDirectory(this.saveFolder);


                            //启动图片来源工作线程，生产者
                            //AutoPictureReg(filePaths);
                            Thread thread = new Thread(new ParameterizedThreadStart(AutoPictureReg));
                            thread.Start(filePaths);
                        }
                        else
                        {
                            MessageBox.Show("源文件夹不存在jpg图片！");
                        }
                    }
                    else
                    {
                        MessageBox.Show("源文件夹不存在！");
                    }
                }
            }
            else//点击结束
            {
                this.endTime = DateTime.Now;
                this.lbTimeSpan.Text = "用时:" + OCR.TimeSpan(this.beginTime, this.endTime, 分秒毫秒.分秒);
                if (this.tsMode.Text == "拍照识别")
                {
                    //关闭自动识别
                    this.autoRecognition = false;
                    // 插入一个Null任务，通知工作线程退出
                    EnqueueTask(null);
                    threadRecognition.Join();  // 等待工作线程完成
                    _wh.Close();
                    //有调整
                    if (CardManager.Cards.Exists(d => d.IsNoDoubt || d.IsPwDoubt))
                    {
                        Adjust frm = new Adjust(this.saveFolder, CardManager.Cards);
                        frm.ShowDialog();//调整结束
                        this.noDoubtCount = 0;
                        this.pwDoubtCount = 0;
                        this.lbNoErrorCount.Text = this.noDoubtCount.ToString();
                        this.lbPwErrorCount.Text = this.pwDoubtCount.ToString();

                    }
                    SaveHistory();
                    this.btStart.Text = "开始";
                    this.btAdjust.Enabled = true;
                    this.btExportExcel.Enabled = true;

                }
                else
                {
                    //关闭自动识别
                    this.autoRecognition = false;
                }
            }
        }
        /// <summary>
        /// 识别结果存储
        /// </summary>
        private void SaveHistory()
        {

            //识别结果对象，用户历史记录
            HistoryInfo history = new HistoryInfo();
            history.Date = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            history.ImageFolder = this.saveFolder;
            history.OcrConfig = this.curCardType;
            //识别结果值
            history.Results = CardManager.Cards;

            List<HistoryInfo> historys = new List<HistoryInfo>();

            if (File.Exists(OCR.HistoryFilePath))
            {
                string str = File.ReadAllText(OCR.HistoryFilePath);
                historys = JsonConvert.DeserializeObject<List<HistoryInfo>>(str);
            }
            historys.Add(history);
            string str1 = JsonConvert.SerializeObject(historys);
            using (System.IO.StreamWriter file = new System.IO.StreamWriter(OCR.HistoryFilePath, false))
            {
                file.WriteLine(str1);
            }
        }
        //导出excel
        private void btExportExcel_Click(object sender, EventArgs e)
        {
            if (this.lbNoErrorCount.Text != "0" || this.lbPwErrorCount.Text != "0")
            {
                MessageBox.Show("有可疑识别，请先调整！");
                return;
            }


            this.sfdOpenFile.Filter = "Excel文件(*.xls)|*.xls";
            this.sfdOpenFile.FileName = DateTime.Now.ToString("yyyy-MM-dd") + "_" + this.curCardType.FaceValue + "(" + CardManager.Cards.Count + ")";
            if (this.sfdOpenFile.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {

                string resultPath = this.sfdOpenFile.FileName;
                //导出excel
                CardManager.ExportExcel(this.saveFolder, resultPath);
                MessageBox.Show("已经存到文件，路径" + resultPath);

            }
        }

        private void btHistory_Click(object sender, EventArgs e)
        {
            Search frm = new Search();
            frm.Show();
        }
        /// <summary>
        /// 新增配置方案
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btAdd_Click(object sender, EventArgs e)
        {
            InputConfigName frm = new InputConfigName(CardTypeManager.CardTypes, this.curCardType.FactoryName + "(" + this.curCardType.FaceValue + ")");
            if (frm.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                this.curCardType = new CardType();
                this.curCardType.Name = frm.ConfigName;
                //方案名称
                this.tbCardTypeName.Text = this.curCardType.Name;
                //根据当前控件值设置当前配置值
                SetCardType(this.curCardType);
                CardTypeManager.AddCardType(this.curCardType);
                //配置控件列表
                FillConfigs();
                //默认选择第一个
                this.cbCardType.SelectedIndex = 0;
                //画区域
                this.pbPreview.Invalidate();
            }
        }
        /// <summary>
        /// 保存当前配置方案
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btSave_Click(object sender, EventArgs e)
        {
            if (this.selectCardType == null)
            {
                this.selectCardType = new CardType();
            }
            //当前选择配置更新为最新
            SetCardType(this.selectCardType);
            //区域赋值
            this.selectCardType.NoRecognition.CharRecognition.Region = this.curCardType.NoRecognition.CharRecognition.Region;
            this.selectCardType.NoRecognition.BarCodeRecognition.Region = this.curCardType.NoRecognition.BarCodeRecognition.Region;
            this.selectCardType.PwRecognition.CharRecognition.Region = this.curCardType.PwRecognition.CharRecognition.Region;
            this.selectCardType.PwRecognition.BarCodeRecognition.Region = this.curCardType.PwRecognition.BarCodeRecognition.Region;
            //噪点赋值
            this.selectCardType.NoRecognition.CharRecognition.NoiseClear = this.curCardType.NoRecognition.CharRecognition.NoiseClear;
            this.selectCardType.NoRecognition.BarCodeRecognition.NoiseClear = this.curCardType.NoRecognition.BarCodeRecognition.NoiseClear;
            this.selectCardType.PwRecognition.CharRecognition.NoiseClear = this.curCardType.PwRecognition.CharRecognition.NoiseClear;
            this.selectCardType.PwRecognition.BarCodeRecognition.NoiseClear = this.curCardType.PwRecognition.BarCodeRecognition.NoiseClear;


            CardTypeManager.Save();
            //填充配置项列表
            FillConfigs();
            //默认上次选择
            this.cbCardType.SelectedIndex = this.configSelectIndex;
            MessageBox.Show("保存成功");
        }
        private void cbFont_SelectedIndexChanged(object sender, EventArgs e)
        {
            ComboBox cb = sender as ComboBox;
            if (this.curCardType != null)
            {
                if (cb.Name == "cbNoFont")
                {
                    this.curCardType.NoRecognition.CharRecognition.Font = this.cbNoFont.Text;
                }
                else if (cb.Name == "cbPwFont")
                {
                    this.curCardType.PwRecognition.CharRecognition.Font = this.cbPwFont.Text;
                }
            }
        }

        private void cbRegType_SelectedIndexChanged(object sender, EventArgs e)
        {
            ComboBox cb = sender as ComboBox;
            if (this.curCardType != null)
            {
                if (cb.Name == "cbNoRegType")
                {
                    this.curCardType.NoRecognition.Type = (识别方法)Enum.Parse(typeof(识别方法), this.cbNoRegType.Text);
                }
                else if (cb.Name == "cbPwRegType")
                {
                    this.curCardType.PwRecognition.Type = (识别方法)Enum.Parse(typeof(识别方法), this.cbPwRegType.Text);
                }
            }
        }

        private void ckbNumCharacter_CheckedChanged(object sender, EventArgs e)
        {
            CheckBox ckb = sender as CheckBox;
            if (this.curCardType != null)
            {
                if (ckb.Name == "ckbNoNum")
                {
                    this.curCardType.NoRecognition.CharRecognition.RecognitionNum = this.ckbNoNum.Checked;
                }
                else if (ckb.Name == "ckbNoCharacter")
                {
                    this.curCardType.NoRecognition.CharRecognition.RecognitionChar = this.ckbNoCharacter.Checked;
                }
                else if (ckb.Name == "ckbPwNum")
                {
                    this.curCardType.PwRecognition.CharRecognition.RecognitionNum = this.ckbPwNum.Checked;
                }
                else if (ckb.Name == "ckbPwCharacter")
                {
                    this.curCardType.PwRecognition.CharRecognition.RecognitionChar = this.ckbPwCharacter.Checked;
                }
            }
        }

        private void nbNoCount_ValueChanged(object sender, EventArgs e)
        {
            if (this.curCardType != null)
            {
                this.curCardType.NoCount = Convert.ToInt32(this.nbNoCount.Value);
            }
        }

        private void nbPwCount_ValueChanged(object sender, EventArgs e)
        {
            if (this.curCardType != null)
            {
                this.curCardType.PwCount = Convert.ToInt32(this.nbPwCount.Value);
            }
        }
        //运营商
        private void cbFactoryName_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this.curCardType != null)
            {
                this.curCardType.FactoryName = this.cbFactoryName.Text;
            }
        }

        private void cbFaceValue_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this.curCardType != null)
            {
                this.curCardType.FaceValue = this.cbFaceValue.Text;
            }
        }

        private void dpValidDate_ValueChanged(object sender, EventArgs e)
        {
            if (this.curCardType != null)
            {
                this.curCardType.ValidDate = this.dpValidDate.Value;
            }
        }

        //private void ckbNoiseClear_CheckedChanged(object sender, EventArgs e)
        //{
        //    CheckBox ckb = sender as CheckBox;
        //    if (this.curCardType != null)
        //    {
        //        if (ckb.Name == "ckbNoCharNoiseClear")
        //        {
        //            this.curCardType.NoRecognition.CharRecognition.NoiseClear = this.ckbNoCharNoiseClear.Checked;
        //            this.pbNoChar.Image = BitmapHelper.CutProcessImage((Bitmap)this.pbPreview.Image, this.noCharRect, BinarizationMethods.Otsu, this.ckbNoCharNoiseClear.Checked); ;
        //            this.pbNoChar.Refresh();
        //        }
        //        else if (ckb.Name == "ckbNoBarCodeNoiseClear")
        //        {
        //            this.curCardType.NoRecognition.BarCodeRecognition.NoiseClear = this.ckbNoBarCodeNoiseClear.Checked;
        //            this.pbNoBarCode.Image = BitmapHelper.CutProcessImage((Bitmap)this.pbPreview.Image, this.noBarCodeRect, BinarizationMethods.Otsu, this.ckbNoBarCodeNoiseClear.Checked); ;
        //            this.pbNoBarCode.Refresh();
        //        }
        //        else if (ckb.Name == "ckbPwCharNoiseClear")
        //        {
        //            this.curCardType.PwRecognition.CharRecognition.NoiseClear = this.ckbPwCharNoiseClear.Checked;
        //            this.pbPwChar.Image = BitmapHelper.CutProcessImage((Bitmap)this.pbPreview.Image, this.pwCharRect, BinarizationMethods.Otsu, this.ckbPwCharNoiseClear.Checked); ;
        //            this.pbPwChar.Refresh();
        //        }
        //        else if (ckb.Name == "ckbPwBarCodeNoiseClear")
        //        {
        //            this.curCardType.PwRecognition.BarCodeRecognition.NoiseClear = this.ckbPwBarCodeNoiseClear.Checked;
        //            this.pbPwBarCode.Image = BitmapHelper.CutProcessImage((Bitmap)this.pbPreview.Image, this.pwBarCodeRect, BinarizationMethods.Otsu, this.ckbPwBarCodeNoiseClear.Checked); ;
        //            this.pbPwBarCode.Refresh();
        //        }
        //    }
        //}
        //图片识别
        private void tsPicture_Click(object sender, EventArgs e)
        {
            this.tsMode.Text = this.tsPicture.Text;
            //加载显示面板
            EnableViewPanel();
        }
        //拍照识别
        private void tsCapture_Click(object sender, EventArgs e)
        {
            this.tsMode.Text = this.tsCapture.Text;
            //显示面板
            EnableViewPanel(); ;
        }


        //显示区域面板
        private void EnableViewPanel()
        {
            if (this.tsMode.Text == "拍照识别")
            {
                //隐藏源文件夹面板
                this.tsSourceFolderFlag.Visible = false;
                this.tsSourceFolder.Visible = false;
                this.tsSourceFolderOperate.Visible = false;

                //去掉图片显示
                this.pbPreview.Image = null;

                //显示拍照识别状态
                this.tsDalayTimeFlag.Visible = true;//拍照延时标签
                this.tsDelayTime.Visible = true;//拍照延时
                this.tsCaptureTimeSpan.Visible = true;//拍照耗时
                this.tsOpaticalSwitchFlag.Visible = true;//光电开关标签
                this.tsSwitchOnOff.Visible = true;//光电开关
                this.tsSwitchCountFlag.Visible = true;//光电计数标签
                this.tsSwitchCount.Visible = true;//光电计数



            }
            else//图片识别
            {
                //隐藏拍照识别状态
                this.tsDalayTimeFlag.Visible = false;
                this.tsDelayTime.Visible = false;
                this.tsCaptureTimeSpan.Visible = false;
                this.tsOpaticalSwitchFlag.Visible = false;
                this.tsSwitchOnOff.Visible = false;
                this.tsSwitchCountFlag.Visible = false;
                this.tsSwitchCount.Visible = false;
                this.lbCaptureTip.Visible = false;
                //显示源文件夹面板
                this.tsSourceFolderFlag.Visible = true;
                this.tsSourceFolder.Visible = true;
                this.tsSourceFolderOperate.Visible = true;

                //显示第一张图片并框选
                if (!string.IsNullOrEmpty(this.tsSourceFolder.Text))
                {
                    ShowFirstPicture();
                }
            }
        }
        /// <summary>
        /// 显示第一张图片并框选及区域图片处理
        /// </summary>
        private void ShowFirstPicture()
        {
            if (Directory.Exists(this.tsSourceFolder.Tag.ToString()))
            {
                string[] filePaths = Directory.GetFiles(this.tsSourceFolder.Tag.ToString(), "*.jpg", SearchOption.TopDirectoryOnly);
                if (filePaths != null && filePaths.Length > 0)
                {
                    this.pbPreview.Image = new Bitmap(filePaths[0]);
                    this.widthRate = (float)this.pbPreview.Size.Width / (float)this.pbPreview.Image.Size.Width;
                    this.heightRate = (float)this.pbPreview.Size.Height / (float)this.pbPreview.Image.Size.Height;
                    //重绘
                    this.pbPreview.Refresh();
                }
                else
                {
                    this.tsTip.Text = "所选择的文件夹没有jpg图片!";
                }
            }
            else
            {
                this.tsTip.Text = "当前文件夹不存在!";
            }
        }

        //选择文件夹
        private void tsSelectFolder_Click(object sender, EventArgs e)
        {
            this.tsSourceFolderOperate.Text = "选择";


            this.folderBrowserDialog1.SelectedPath = this.tsSourceFolder.Tag.ToString();

            if (this.folderBrowserDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                this.tsSourceFolder.Tag = this.folderBrowserDialog1.SelectedPath;
                this.tsSourceFolder.Text = Path.GetPathRoot(this.folderBrowserDialog1.SelectedPath) + @"...\" + Path.GetFileName(this.folderBrowserDialog1.SelectedPath);
                this.tsTip.Text = "就绪...点击【开始】识别图片";
                //保存当前值
                Properties.Settings.Default.SourceFoldPath = this.tsSourceFolder.Tag.ToString();
                Properties.Settings.Default.Save();
                //显示第一张图并框选
                ShowFirstPicture();
            }
        }
        //打开文件夹
        private void tsOpenFolder_Click(object sender, EventArgs e)
        {
            this.tsSourceFolderOperate.Text = "打开";
            if (Directory.Exists(this.tsSourceFolder.Tag.ToString()))
            {
                Process.Start(this.tsSourceFolder.Tag.ToString());
            }
            else
            {
                Process.Start(@"d:\");
            }

        }
        private void tsSourceFolderOperate_ButtonClick(object sender, EventArgs e)
        {
            if (this.tsSourceFolderOperate.Text == "选择")
            {
                this.tsSelectFolder_Click(null, null);
            }
            else
            {
                this.tsOpenFolder_Click(null, null);
            }
        }

        private void btCancel_Click(object sender, EventArgs e)
        {
            this.plSelection.Visible = false;
            this.scContent.Panel2.Enabled = true;
            this.plTop.Enabled = true;
            this.pbPreview.Refresh();
        }

        private void tsTrain_Click(object sender, EventArgs e)
        {
            Train frm = new Train();
            frm.Show();
        }

        private void NewMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (this.btStart.Text == "结束")
            {
                MessageBox.Show("识别未结束，不能关闭程序");
                e.Cancel = true;
            }
            else
            {
                this.cameraControl.CloseCamera();
                if (_wh != null)
                {
                    _wh.Close();            // 释放资源
                }

            }

        }


        private void pbPreview_Resize(object sender, EventArgs e)
        {
            if (this.pbPreview.Image != null)
            {
                this.widthRate = (float)this.pbPreview.Size.Width / (float)this.pbPreview.Image.Size.Width;
                this.heightRate = (float)this.pbPreview.Size.Height / (float)this.pbPreview.Image.Size.Height;
            }

        }

        private void tsShowRegionView_Click(object sender, EventArgs e)
        {
            if (this.regionView == null)
            {
                this.regionView = new RegionView(this.curCardType, (Bitmap)this.pbPreview.Image);
                this.regionView.Show();
            }
            else
            {
                this.regionView.ShowImage(this.curCardType, (Bitmap)this.pbPreview.Image);
                this.regionView.Visible = true;
            }
        }

        private void cmPicture_Opening(object sender, CancelEventArgs e)
        {
            if (this.pbPreview.Image == null)
            {
                this.tsShowRegionView.Enabled = false;
            }
            else
            {
                this.tsShowRegionView.Enabled = true;
            }
        }

        private void cmCamera_Opening(object sender, CancelEventArgs e)
        {
            if (!this.cameraControl.CameraCreated)
            {
                this.tsCameraSource.Enabled = false;
                this.tsPix.Enabled = false;
                this.tsCapturePicture.Enabled = false;
            }
            else
            {
                this.tsCameraSource.Enabled = true;
                this.tsPix.Enabled = true;
                this.tsCapturePicture.Enabled = true;
            }
        }

        private void btSetting_Click(object sender, EventArgs e)
        {
            About frm = new About();
            frm.ShowDialog();
        }
    }
}
